
const express = require('express');
const multer = require('multer');
const exphbs = require('express-handlebars'); // 引入 hanlebars 解析
const fs = require("fs");
const app = express();
const bodyParser = require('body-parser'); // 引入body-parser模块
const multipart = require('connect-multiparty');//引入connect-multiparty模块
const path = require('path');
const { request } = require("http");

 // 设置模板为 handlebars
 app.set('views', path.join(__dirname, 'views'));
 const hbs = exphbs.create({
    extname: '.html', // 设置文件后缀
    layoutsDir: ['views/'] // 设置模板文件的目录
 })
 app.engine('hbs', hbs.engine); // 设置其模板引擎，名称为 'hbs'
 app.set('view engine', 'hbs'); // 将当前默认模板引擎设置为 ’hbs‘

// 设置存储配置
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, 'uploads/') // 确保这个文件夹已经存在
    },
    filename: function (req, file, cb) {
     // console.log(file)  
     let mimetype = getFileExtension(file.originalname);//获取文件后缀
      cb(null, file.fieldname + '-' + Date.now()+mimetype)
    }
  })
   
  const upload = multer({ storage: storage });
   
  // 处理上传的图片
  app.post('/upload', upload.single('file'), (req, res) => {
    const file = req.file;
    if (!file) {
      return res.status(400).send('No file uploaded.');
    }
    res.send({code:200,url:encodeURI('/uploads/'+file.filename)});
  });
  //获取文件后缀
function getFileExtension(filename) {
    let mimetype = filename.split('.').pop();
    mimetype = mimetype?'.'+mimetype :'';
    return mimetype;
}

var Datastore = require('nedb');
  
app.use(express.static(__dirname));
app.use(bodyParser.json()); // 解析json数据格式
app.use(bodyParser.urlencoded({extended: true})); // 解析form表单提交的数据application/x-www-form-urlencoded
app.use(multipart());//解析form-data提交数据

function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay)
        ;
}

function ShowTagData(data){

}

function uint8Arrays(uint8Array) {
    return Array.prototype.map
      .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
      .join('');
}
app.get("/dist", (request, response) => {
    fs.readFile("./dist/index.html" , (err, data) => {
        // body
        if (err) {
            console.log(err);
            //404：NOT FOUND
            response.writeHead(404, { "Content-Type": "text/html" });
        }
        else {
            //200：OK
            response.writeHead(200, { "Content-Type": "text/html" });
            response.write(data.toString());
        }
        response.end();
    });
});
//产品信息
app.get("/index",(request,response)=>{
    // 向页面传递数据
    const data = {
        title: '首页',
        message: '欢迎访问我的网站！'
    };
    response.render('index', data);
    // fs.readFile("./view/index.html" , (err, data) => {
    //     // body
    //     if (err) {
    //         console.log(err);
    //         //404：NOT FOUND
    //         response.writeHead(404, { "Content-Type": "text/html" });
    //     }
    //     else {
    //         //200：OK
    //         response.writeHead(200, { "Content-Type": "text/html" });
    //         response.write(data.toString());
    //     }
    //     response.end();
    // });

})
//城市数据
app.get("/city",(request,response)=>{
      // 向页面传递数据
      let data = [];
      let db = new Datastore({ filename: 'db/datafile', autoload: true });
      db.find({}).sort({ sort: -1 }).exec(function (err, docs) {

        data = docs
       
       response.render('city', {"list":data});
    });
  
    // fs.readFile("./view/city.html" , (err, data) => {
    //     // body
    //     if (err) {
    //         console.log(err);
    //         //404：NOT FOUND
    //         response.writeHead(404, { "Content-Type": "text/html" });
    //     }
    //     else {
    //         //200：OK
    //         response.writeHead(200, { "Content-Type": "text/html" });
    //         response.write(data.toString());
    //     }
    //     response.end();
    // });

})
app.get("/getdata",(request,response)=>{
        // 查询所有结果集
       let db = new Datastore({ filename: 'db/datafile', autoload: true });
        console.log(request.query.limit); 
        var page =  request.query.page??1
        var size =  request.query.limit??10
        var startnum = (page-1)*size 
        var counts = 0
    db.count({}, function (err, count) {
        // count equals to 4
            counts = count
        });
    db.find({}).sort({ sort: -1 }).skip(startnum).limit(size).exec(function (err, docs) {
        
        response.writeHead(200, { "Content-Type": "text/html" });
        var result = {code:0,msg:'success',count:counts,data:docs}
        //$list = ['code' => $code, 'data' => $data, 'count' => $count, 'msg' => $msg];
        response.write(JSON.stringify(result));
        response.end();
    });
 
})
//编辑产品
app.post("/setdata", (request, response) => {
        //console.log(request.body);
       let db = new Datastore({ filename: 'db/datafile', autoload: true });
        // 查询单项
        db.findOne({
            _id: request.body._id
        }, (err, ret) => {
            console.log(err,ret,"查询")
            if(ret){
               
                // 更新单项
                db.update({
                    _id: ret._id
                }, {
                    
                    $set: {
                        ...request.body
                    }
                }, (err, ret) => {});    
            }
        });
       
        response.writeHead(200, { "Content-Type": "text/html" });
       
        response.end(JSON.stringify({code:1,msg:'success'}));
    
});
//获取城市数据
app.get("/getCity", (request, response) => {
          // 查询所有结果集
       let db = new Datastore({ filename: 'db/datacity', autoload: true });
       console.log(request.query.limit); 
       var page =  request.query.page??1
       var size =  request.query.limit??10
       var startnum = (page-1)*size 
       var pid = request.query.pid??"" 
       var city = request.query.city??"" 
       var counts = 0
       let query = {}
       if(city){
           query.city = { $eq: city }
       }
       if(pid){
        query.pid = { $eq: pid }
    }
        db.count(query, function (err, count) {
            // count equals to 4
                counts = count
            });
        db.find(query).sort({ sort: -1 }).skip(startnum).limit(size).exec(function (err, docs) {
            
            response.writeHead(200, { "Content-Type": "text/html" });
            var result = {code:0,msg:'success',count:counts,data:docs}
            //$list = ['code' => $code, 'data' => $data, 'count' => $count, 'msg' => $msg];
            response.write(JSON.stringify(result));
            response.end();
        });
});
app.listen(3000, '127.0.0.1', () => {
    console.log(`Server running at http://127.0.0.1:3000/`)

})
